<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="学生姓名" prop="student">
        <el-input
          v-model="queryParams.student"
          placeholder="请输入学生姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="课程名称" prop="subject">
        <el-input
          v-model="queryParams.subject"
          placeholder="请输入课程名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['edu:schedule:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-location-information"
          size="mini"
          :disabled="multiple"
          @click="handleQuickClockIn"
        >快速打卡
        </el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['edu:schedule:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="scheduleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="学生姓名" align="center" prop="student"/>
      <el-table-column label="课程名称" align="center" prop="subject"/>
      <el-table-column label="课程价格" align="center" prop="classPrice"/>
      <el-table-column label="课时" align="center" prop="classNum"/>
      <el-table-column label="剩余课时" align="center" prop="remainingClassNum"/>
      <el-table-column label="机构名称" align="center" prop="tenantName"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['edu:schedule:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-location-information"
            @click="handleClockIn(scope.row)"
          >打卡
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-notebook-2"
            @click="handleStudyRecord(scope.row)"
          >上课记录
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['edu:schedule:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改学生课时对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="姓名" prop="student">
              <el-input v-model="form.student" placeholder="请输入姓名" :disabled="form.id  != null">
                <el-button v-if="form.id == null" type="primary" slot="append" icon="el-icon-search"
                           @click="selectStudentOpen = true"
                >选择
                </el-button>
                <el-button v-if="form.id == null" type="primary" slot="append" icon="el-icon-plus"
                           @click="addStudentOpen = true"
                >新增
                </el-button>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="生日" prop="birthday">
              <el-date-picker clearable v-model="form.birthday" type="date" style="width: 100%"
                              value-format="yyyy-MM-dd" placeholder="请选择生日"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-select v-model="form.gender" placeholder="请选择性别" style="width: 100%">
                <el-option v-for="dict in dict.type.sys_user_sex" :key="dict.value" :label="dict.label"
                           :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="联系人" prop="guardian">
              <el-input v-model="form.guardian" placeholder="请输入监护人"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="guardianPhone">
              <el-input v-model="form.guardianPhone" placeholder="请输入监护人电话"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="班级" prop="roomName">
              <el-input v-model="form.roomName" placeholder="请选择班级" disabled>
                <el-button type="primary" slot="append" icon="el-icon-search" @click="classRoomOpen = true">选择</el-button>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="课程名称" prop="subjectId">
              <el-select v-model="form.subjectId" placeholder="请选择课程" style="width: 100%">
                <el-option v-for="item in subjectOptions" :key="item.id" :label="item.subjects" :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="课程价格" prop="classPrice">
              <el-input v-model="form.classPrice" placeholder="请输入课程价格"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="课时" prop="classNum">
              <el-input v-model="form.classNum" placeholder="请输入课时"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="剩余课时" prop="remainingClassNum">
              <el-input v-model="form.remainingClassNum" placeholder="请输入剩余课时"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="打卡签到" :visible.sync="clockInOpen" width="1000px" append-to-body>
      <el-form ref="clockInForm" :model="clockInForm" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="快捷模板" prop="quickTemplate">
              <el-select v-model="quickTemplate" placeholder="快捷模板" style="width: 100%">
                <el-option v-for="item in quickTemplateOptions" :key="item.id" :label="item.templateContent" :value="item.templateContent">
                  <span style="float: left">{{ item.templateType }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px" v-html=" item.vatemplateContentlue "></span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="老师寄语" prop="studyRecord">
              <el-input v-model="clockInForm.studyRecord" type="textarea"  placeholder="请输入内容"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="资料影像" prop="studyRecord">
              <el-upload ref="upload" list-type="picture-card" :auto-upload="false" accept=".jpg, .png" :limit="1"
                         :headers="upload.headers"
                         :action="upload.url + '?studyRecord=' + clockInForm.studyRecord + '&scheduleId=' + clockInForm.scheduleId"
                         :disabled="upload.isUploading" :on-progress="handleFileUploadProgress"
                         :on-success="handleFileSuccess"
              >
                <i slot="default" class="el-icon-plus"></i>
                <div slot="file" slot-scope="{file}">
                  <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
                  <span class="el-upload-list__item-actions">
                    <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                      <i class="el-icon-zoom-in"></i>
                    </span>
                    <!--                    <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleDownload(file)">-->
                    <!--                      <i class="el-icon-download"></i>-->
                    <!--                    </span>-->
                    <span v-if="!disabled" class="el-upload-list__item-delete" @click="handlePictureRemove(file)">
                      <i class="el-icon-delete"></i>
                    </span>
                  </span>
                </div>
              </el-upload>
              <el-dialog :visible.sync="dialogVisible" :modal="false" :lock-scroll="false">
                <img width="100%" :src="dialogImageUrl" alt="">
              </el-dialog>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="clockInCancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 学生选择组件 -->
    <select-student-dialog
      :visible.sync="selectStudentOpen"
      @select="handleStudentSelected"
    />
    <!--班级选择组件-->
    <select-class-room-dialog
      :visible.sync="classRoomOpen"
      @select="handleClassRoomSelected"
    />
    <add-student-dialog  :visible.sync="addStudentOpen"
                         @addSuccess="handleStudentSelected"/>
  </div>
</template>

<script>
import { listSchedule, getSchedule, delSchedule, addSchedule, updateSchedule, quickClockIn } from '@/api/edu/studentSchedule'
import { listSubjects } from '@/api/edu/subjects'
import { listTemplate } from '@/api/edu/template'
import { getToken } from '@/utils/auth'
import SelectStudentDialog from '@/views/edu/components/SelectStudentDialog'
import SelectClassRoomDialog from '@/views/edu/components/SelectClassRoomDialog.vue'
import addStudentDialog from '@/views/edu/components/addStudentDialog.vue'

export default {
  name: 'studentSchedule',
  dicts: ['sys_user_sex'],
  components: {
    SelectStudentDialog,SelectClassRoomDialog,addStudentDialog
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      studentLoading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      studentTotal: 0,
      quickTemplate: "",
      // 学生课时表格数据
      scheduleList: [],
      // 学生数据
      studentList: [],
      quickTemplateOptions: [],
      // 课程数据
      subjectOptions: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      selectStudentOpen: false,
      addStudentOpen: false,
      classRoomOpen: false,
      clockInOpen: false,
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        studentId: null,
        student: null,
        subjectId: null,
        subject: null,
        classPrice: null,
        classNum: null,
        remainingClassNum: null,
        tenantId: null,
        tenantName: null
      },
      selectedStudentRow: null,
      // 表单参数
      form: {},
      clockInForm: {},
      upload: {
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/edu/schedule/clockIn'
      },
      // 表单校验
      rules: {
        student: [
          { required: true, message: '姓名不能为空', trigger: 'blur' }
        ],
        guardian: [
          { required: true, message: '联系人不能为空', trigger: 'blur' }
        ],
        guardianPhone: [
          { required: true, message: '联系电话不能为空', trigger: 'blur' }
        ],
        subjectId: [
          { required: true, message: '课程不能为空', trigger: 'blur' }
        ],
        classPrice: [
          { required: true, message: '课程价格不能为空', trigger: 'blur' }
        ],
        classNum: [
          { required: true, message: '课时不能为空', trigger: 'blur' }
        ],
        remainingClassNum: [
          { required: true, message: '剩余课时不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
    this.getSubjectList()
  },
  watch: {
    'form.subjectId'(newVal, oldVal) {
      const subject = this.subjectOptions.find(subject => subject.id == newVal)
      if (subject) {
        this.form.subject = subject.subjects
        this.form.classPrice = subject.subjectPrices
        this.form.classNum = subject.classNum
        this.form.remainingClassNum = subject.classNum
      }
    }
  },
  methods: {
    getQuickTemplateOptions(){
      listTemplate({  }).then(response => {
        this.templateList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询课程列表 */
    getSubjectList() {
      let subjectQuery = {
        subjectStatus: 1
      }
      listSubjects(subjectQuery).then(response => {
        this.subjectOptions = response.rows
      })
    },
    /** 查询学生课时列表 */
    getList() {
      this.loading = true
      listSchedule(this.queryParams).then(response => {
        this.scheduleList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    clockInCancel() {
      this.clockInOpen = false
      this.$refs.upload.clearFiles()
      this.resetClockIn()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        studentId: null,
        student: null,
        subjectId: null,
        subject: null,
        classPrice: null,
        classNum: null,
        remainingClassNum: null,
        roomId: null,
        roomName: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        tenantId: null,
        tenantName: null
      }
      this.resetForm('form')
    },
    // 表单重置
    resetClockIn() {
      this.clockInForm = {
        id: null,
        studyRecord: null
      }
      this.resetForm('clockInForm')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加学生课时'
    },
    handleClockIn(row) {
      this.resetClockIn()
      this.clockInForm.scheduleId = row.id
      this.clockInOpen = true
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getSchedule(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = '修改学生课时'
      })
    },
    handleQuickClockIn(row) {
      const id = row.id || this.ids
      quickClockIn(id).then(response => {
        this.getList()
        this.$modal.msgSuccess('打卡成功')
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateSchedule(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addSchedule(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除学生课时编号为"' + ids + '"的数据项？').then(function() {
        return delSchedule(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('edu/schedule/export', {
        ...this.queryParams
      }, `schedule_${new Date().getTime()}.xlsx`)
    },
    handlePictureRemove(file) {
      // 1. 先移除本地列表
      this.$refs.upload.handleRemove(file)
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleDownload(file) {
      console.log(file)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.clockInOpen = false
      this.resetClockIn()
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      this.$alert('<div style=\'overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;\'>' + response.msg + '</div>', '打卡结果', { dangerouslyUseHTMLString: true })
      this.getList()
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit()
    },
    handleStudyRecord(row) {
      this.$router.push('/record/index/' + row.id)
    },
    // 处理学生选择
    handleStudentSelected(student) {
      this.form.studentId = student.id
      this.form.student = student.name
      this.form.gender = student.gender
      this.form.guardian = student.guardian
      this.form.birthday = student.birthday
      this.form.guardianPhone = student.guardianPhone
    },

    handleClassRoomSelected(classRoom) {
      this.form.roomId = classRoom.id;
      this.form.roomName = classRoom.className;
      this.form.subjectId = classRoom.subjectId;
    }
  }
}
</script>
